
package com.zktravel.util;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;

public final class JsonHelper {
	
	private JsonHelper() {
		
	}
	
	/**
	 * JSON转化为对象
	 * 
	 * @param <T>
	 * @param json
	 * @param beanClass
	 * @return
	 */
	public static <T> T json2Bean(String json, Class<T> beanClass) {
		return JSON.parseObject(json, beanClass);
	}
	
	/**
	 * JSON转化为对象。处理泛型问题
	 * 
	 * @param <T>
	 * @param json
	 * @param typeRef
	 * @return
	 */
	public static <T> T json2Bean(String json, TypeReference<T> typeRef) {
		return JSON.parseObject(json, typeRef);
	}

	/**
	 * JSON转化为List
	 * 
	 * @param <T>
	 * @param json
	 * @param beanClass
	 * @return
	 */
	public static <T> List<T> json2List(String json, Class<T> beanClass) {
		return JSON.parseArray(json, beanClass);
	}

	/**
	 * 把一个对象转换为JSON格式数据
	 * 
	 * @param bean
	 * @param features
	 * @return
	 */
	public static String bean2Json(Object bean, SerializerFeature... features) {
		
		return JSON.toJSONString(bean, features);
	}
	
	public static String bean2Json(Object obj){
		return JSON.toJSONString(obj);
	}
	
	/**
	 * 把一个对象转换为JSON格式数据
	 * @param bean
	 * @param includeFields
	 * @param features
	 * @return
	 */
	public static String bean2JsonWithIncludes(Object bean, String[] includeFields, SerializerFeature... features) {
		PropertyPreFilter filter = new SimplePropertyPreFilterExt(includeFields, null); 
		return JSON.toJSONString(bean, filter, features);
	}
	
	/**
	 * 把一个对象转换为JSON格式数据
	 * @param bean
	 * @param excludeFields
	 * @param features
	 * @return
	 */
	public static String bean2JsonWithExcludes(Object bean, String[] excludeFields, SerializerFeature... features) {
		PropertyPreFilter filter = new SimplePropertyPreFilterExt(null, excludeFields); 
		return JSON.toJSONString(bean, filter, features);
	}
	
	/**
	 * 把一个对象转换为JSON格式数据, exludeFields优先级高于includeFields
	 * 
	 * @param bean
	 * @param excludeFields 
	 * @param includeFields
	 * @param features
	 * @return
	 */
	public static String bean2Json(Object bean, String[] excludeFields, String[] includeFields, SerializerFeature... features) {
		PropertyPreFilter filter = new SimplePropertyPreFilterExt(includeFields, excludeFields); 
		return JSON.toJSONString(bean, filter, features);
	}
	
}
